package no.ntnu.fp.messages.impl;

import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.utils.XmlParser;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class AddOrUpdateAppointmentMessage implements Message {
	private final Appointment appointment;
	private final UpdateType updateType;
	
	public enum UpdateType { ADD, UPDATE }

	public AddOrUpdateAppointmentMessage(Appointment appointment, 
											UpdateType type) {
		this.appointment = appointment;
		this.updateType = type;
	}

	public AddOrUpdateAppointmentMessage() { 
		this(null, null);
	}

	public Appointment getAppointment() {
		return appointment;
	}

	public UpdateType getUpdateType() {
		return updateType;
	}

	@Override
	public MessageCode getMessageCode() {
		return MessageCode.ADD_OR_UPDATE_APPOINTMENT_MESSAGE;
	}

	@Override
	public Message fromXmlString(String xml) {
		Document document = XmlParser.parseXmlString(xml);
		Element appointmentElement = (Element)document.getElementsByTagName("appointment").item(0);
		UpdateType type = UpdateType.valueOf(
				XmlParser.getTextValue(
							(Element)document.getElementsByTagName("message").item(0),
							"updatetype")
				);
		Appointment appointment = new Appointment(appointmentElement);
		return new AddOrUpdateAppointmentMessage(appointment, type);
	}

	@Override
	public String toString() {
		Document document = XmlParser.getThreadLocalDocumentBuilder().newDocument();
		
		Element root = document.createElement("message");
		root.appendChild(XmlParser.createElementWithValue(
				document, "updatetype", this.updateType.toString()));
		Element appointment = this.appointment.toXml(document);
		root.appendChild(appointment);
		
		return getMessageCode() + XmlParser.convertXmlToString(root);
	}
}
